<script setup>
  import { nextTick, reactive, ref, watch, computed } from 'vue'
  import menuSub from './menu-sub.vue'
  import router from '@/router'
  import { projectStore } from '@/store/project'
  import { menuStore } from '__store/menu'

  const [current, opens] = [ref(), ref()]
  const menuRef = ref()

  function onClick(name) {
    if (name) router.push({ name })
  }

  function checkCurrent() {
    let menuDic = menuStore().dic
    if (current.value && Object.keys(menuDic).length) {
      let item = menuDic[current.value]
      if (item) {
        if (item.type == 'project' && !projectStore().info) {
          router.goRoot()
          menuStore().choiceRoot()
        } else {
          if (menuStore().type != item.type) menuStore().choiceType(item.type)
          if (item.root) {
            let rs = item.root.split('/')
            let roots = []
            rs.forEach((r) => {
              roots.push(roots.length > 0 ? roots[roots.length - 1] + '/' + r : r)
            })
            opens.value = roots
            nextTick(() => {
              menuRef.value.updateOpened()
              menuRef.value.updateActiveName()
            })
          } else {
            let roots = [item.title]
            opens.value = roots
            nextTick(() => {
              menuRef.value.updateOpened()
              menuRef.value.updateActiveName()
            })
          }
        }
      } else {
        let item = menuStore().first
        if (item) {
          router.replace({ name: item.name })
        } else {
          router.goLogin()
        }
      }
    }
  }

  watch(
    () => router.currentRoute.value,
    (route) => {
      current.value = route.meta.menuName || route.meta.name
      checkCurrent()
    },
    { immediate: true }
  )
  watch(
    () => menuStore().dic,
    (route) => {
      checkCurrent()
    }
  )
</script>

<template>
  <Menu
    ref="menuRef"
    theme="dark"
    accordion
    width="200px"
    @on-select="onClick"
    :active-name="current"
    :open-names="opens">
    <menu-sub v-for="i in menuStore().items" :key="i.name" :item="i" />
  </Menu>
</template>

<style scoped lang="scss">
  @import url('@/assets/css/sider.scss');
</style>
